extends Area2D

# 轮廓线引用
@onready var outline: Line2D = $Outline
@onready var fill_polygon: Polygon2D = $FillPolygon  # 新增：填充多边形

var outline_alpha: float = 0.0  # 轮廓透明度
var fill_alpha: float = 0.0     # 填充透明度
var fade_speed: float = 4.0     # 淡入淡出速度（从1.0增加到4.0，加快4倍）
var fade_out_speed: float = 1.5 # 单独控制淡出速度，比淡入慢一些
var outline_timer: float = 0.0
var was_scanned: bool = false  # 是否被光环扫描过
var scan_start_time: float = 0.0  # 记录被扫描的时间点

func _ready():
	add_to_group("obstacle")
	# 设置碰撞层
	var collision = get_node_or_null("CollisionPolygon2D")
	if collision:
		collision_layer = 2
		collision_mask = 2
	
	# 初始化轮廓
	if outline:
		outline.visible = true
		outline.default_color = Color.BLACK
		outline.width = 6.0
		outline_alpha = 0.0
		update_outline_alpha()
	
	# 初始化填充
	if fill_polygon:
		fill_polygon.visible = true
		fill_polygon.color = Color.BLACK
		fill_alpha = 0.0
		update_fill_alpha()
	
	# 根据碰撞形状生成轮廓和填充
	generate_from_collision()

func generate_from_collision():
	var collision = $CollisionPolygon2D
	if collision and collision.polygon.size() > 0:
		# 生成轮廓线
		if outline:
			outline.clear_points()
			for point in collision.polygon:
				outline.add_point(point)
			if collision.polygon.size() > 1:
				outline.add_point(collision.polygon[0])
		
		# 生成填充多边形
		if fill_polygon:
			fill_polygon.polygon = collision.polygon

func _process(delta):
	# 检测鼠标左键是否按住
	global_position.x -= 10 * delta * 60
	
	# 移出屏幕时删除
	#if global_position.x < -1000:
	#   queue_free()
	
	# 处理透明度
	update_transparency(delta)
	
	# 处理被扫描后的计时
	if was_scanned:
		outline_timer -= delta
		if outline_timer <= 0:
			was_scanned = false
			scan_start_time = 0.0

func update_transparency(delta):
	var target_alpha: float = 0.0
	
	if was_scanned:
		# 被扫描时目标透明度为1.0
		target_alpha = 1.0
		
		# 使用不同的速度进行淡入和淡出
		var current_speed = fade_speed  # 默认使用淡入速度
		
		# 如果在淡出阶段（计时器后半段），使用淡出速度
		if outline_timer < 2.0:
			current_speed = fade_out_speed
		
		# 平滑过渡到目标透明度
		outline_alpha = move_toward(outline_alpha, target_alpha, current_speed * delta)
		fill_alpha = move_toward(fill_alpha, target_alpha * 0.9, current_speed * delta)
	else:
		# 未被扫描时，淡出到透明
		outline_alpha = move_toward(outline_alpha, 0.0, fade_out_speed * delta)
		fill_alpha = move_toward(fill_alpha, 0.0, fade_out_speed * delta)
	
	# 更新实际透明度
	update_outline_alpha()
	update_fill_alpha()

func update_outline_alpha():
	if outline:
		var color = outline.default_color
		color.a = outline_alpha
		outline.default_color = color

func update_fill_alpha():
	if fill_polygon:
		var color = fill_polygon.color
		color.a = fill_alpha
		fill_polygon.color = color

# 被光环扫描到的方法
func on_scanned():
	if !was_scanned:
		# 首次被扫描时，重置计时器并记录时间
		was_scanned = true
		outline_timer = 2.5  # 显示时间从4秒减少到2.5秒
		scan_start_time = Time.get_ticks_msec() / 1000.0
		
		# 立即设置一个较高的起始透明度，让淡入更快
		outline_alpha = 0.4  # 从40%透明度开始淡入
		fill_alpha = 0.35    # 填充从35%开始淡入
	else:
		# 如果已经在显示中，刷新计时器
		outline_timer = 2.5  # 重新计时2.5秒
